package com.connector.server.handler;

import org.slf4j.LoggerFactory;
import com.connector.base.message.model.ErrorMessage;
import com.connector.server.util.SendMsgUtil;
import com.connector.server.jmx.JmxMessageBean;
import io.netty.channel.ChannelFutureListener;
import com.connector.base.utils.ErrorCode;
import com.connector.base.message.model.BaseMessage;
import com.google.common.base.Strings;
import com.connector.base.connection.Connection;
import com.connector.base.protocol.Packet;
import org.slf4j.Logger;
import com.connector.base.message.model.ChatMessage;
import com.connector.base.handler.BaseMessageHandler;

public class ChatHandler extends BaseMessageHandler<ChatMessage>
{
    private static final Logger log;
    
    public ChatMessage decode(final Packet packet, final Connection connection) {
        return new ChatMessage(packet, connection);
    }
    
    public void handle(final ChatMessage message) {
        if (Strings.isNullOrEmpty(message.getDeviceId())) {
            BaseMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.INVALID_DEVICE).buildResult("Param invalid", "没有找到设备标识！").close();
            ChatHandler.log.error("chat failure, message={}, conn={}", (Object)message, (Object)message.getConnection());
            return;
        }
        try {
            BaseMessage.buildSuccessResponse(message.getConnection()).channelSend((ChannelFutureListener)null);
            ChatHandler.log.info("send chat response success,chat={}", (Object)message);
            message.setPcOrApp(Boolean.valueOf(true));
            SendMsgUtil.sendMsg(JmxMessageBean.build(message));
        }
        catch (Throwable e) {
            ErrorMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.CHAT_FAILURE).buildResult(e.getMessage(), "构建响应失败！").close();
            ChatHandler.log.error("chat failure!", e);
        }
    }
    
    static {
        log = LoggerFactory.getLogger((Class)ChatHandler.class);
    }
}
